package com.crishne.anwo.service.impl;

import com.crishne.anwo.dao.ContentDao;
import com.crishne.anwo.dto.Pager;
import com.crishne.anwo.model.Content;
import com.crishne.anwo.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基本CURD操作在MybatisBaseServiceImpl中实现 否则自行声明接口，实现方法
 */
@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private ContentDao baseDao;

	@Override
	public Content getById(String pk) {
		return baseDao.getById(pk);
	}

	@Override
	public int getTotalCount(Content obj) {
		if (null == obj) {
			throw new NullPointerException("entity bean is null");
		}

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("model", obj);

		return baseDao.getTotalCount(params);
	}

	@Override
	public List<Content> findList(Content obj) {
		if (null == obj) {
			throw new NullPointerException("entity bean is null");
		}

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("model", obj);

		return baseDao.findList(params);
	}

	@Override
	public Pager findPageList(Content obj, Integer pageNumber, Integer pageSize) {
		int total = getTotalCount(obj);
		pageSize = pageSize == null || pageSize <= 0 ? 10 : pageSize;
		int totalPage = (total + pageSize - 1) / pageSize;
		pageNumber = pageNumber == null || pageNumber < 1 ? 1 : pageNumber > totalPage ? totalPage : pageNumber;
		Pager pager = new Pager(pageNumber, pageSize, total);
		if (total > 0) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("offset", (pager.getPageNumber() - 1) * pageSize);
			params.put("rows", pageSize);
			params.put("model", obj);

			List<Content> list = baseDao.findPageList(params);

			pager.setDatas(list); // 数据库集合
		}

		return pager;
	}

	@Override
	public int save(Content obj) {
		if (null == obj) {
			throw new NullPointerException("entity bean is null");
		}

		return baseDao.save(obj);
	}

	@Override
	public int update(Content obj) {
		if (null == obj) {
			throw new NullPointerException("entity bean is null");
		}

		return baseDao.update(obj);
	}

	@Override
	public int delete(String pk) {

		return baseDao.delete(pk);
	}

	@Override
	public int remove(Content obj) {
		if (null == obj) {
			throw new NullPointerException("entity bean is null");
		}

		return baseDao.remove(obj);
	}
}
